<?php

//盲盒相关
namespace App\Http\Controllers\Admin;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GiftBoxController extends BaseController
{
    public $tongKey = 'BLIND_INJECT_TONG';
    public $YingKey = 'BLIND_INJECT_YING';
    public $JinKey = 'BLIND_INJECT_JIN';
    public $type, $pot_name,$price;

    public function __construct(Request $request) {
        $this->type = $request->input('type', 1);
        switch ($this->type) {
            case 1:
                $this->pot_name = '银盲盒';
                $this->price = app('model_gift')->where('type', 5)->value('price');
                break;
            case 2:
                $this->pot_name = '铜盲盒';
                $this->price = app('model_gift')->where('type', 4)->value('price');
                break;
            case 3:
                $this->pot_name = '金盲盒';
                $this->price = app('model_gift')->where('type', 13)->value('price');
                break;
            case 4:
                $this->pot_name = '铜 (背包)';
                break;
            case 5:
                $this->pot_name = '银 (背包)';
                break;
            case 6:
                $this->pot_name = '金 (背包)';
                break;
            case 7:
                $this->pot_name = '铜盲盒';
                break;
            case 8:
                $this->pot_name = '银盲盒';
                break;
            case 9:
                $this->pot_name = '金盲盒';
                break;
            default:
                $this->pot_name = '银盲盒';
                $this->price = app('model_gift')->where('type', 5)->value('price');
        }
    }

    /**
     * @api {Get} /giftbox/getallboxgift 根据奖池类型获取所有礼物
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} pond_type 奖池类型（默认8），2：幸运树游戏-特殊独立奖池；6：病毒大作战-boss血量；8：个人奖池，病毒大作战盲盒奖品
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 283,
    "name": "蓝色夏威夷"
    },
    {
    "id": 288,
    "name": "玩具小熊"
    },
    {
    "id": 299,
    "name": "紫水晶"
    },
    {
    "id": 300,
    "name": "小金表"
    }
    ]
    }
     */
    public function getAllBoxGift(Request $request)
    {
        $pondType = $request->pond_type ?: 8; //奖池类型
        $giftName = $request->input('gift_name', '');
        $condition = [];
        if(!empty($giftName)){
            $condition[] = ['name', 'like', "%{$giftName}%"];
        }
//        $condition[] = ['sold', '=', 1];
        $giftList = app('model_gift')->getAllGift($pondType, ['id', 'asc'], $condition);
        return Response::sendData($giftList);
    }

    /**
     * @api {Post} /giftbox/addboxgift 新增盲盒奖池礼物
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} box_type 盲盒类型：7：铜；8：银；9：金
     * @apiParam {Int} pond_type 奖池类型
     * @apiParam {Int} gift_id 礼物id
     * @apiParam {Int} num 礼物数量
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function addBoxGift(Request $request)
    {
        $boxType = $request->box_type; //盲盒类型：7：铜；8：银；9：金
        $pondType = $request->pond_type; //奖池类型
        $giftId = $request->gift_id; //礼物id
        $giftNum = $request->num; //礼物数量

        //获取盲盒的所有奖池类型
        $pondTypes = self::getPondTypesByBoxType($boxType);
        if (!in_array($pondType, $pondTypes)) {
            throw new BasicException(10001);
        }

        $this->paramVerify($giftId, $giftNum, $pondType);

        $data = [
            'p_type' => $boxType,
            'type' => $pondType,
            'gift_id' => $giftId,
            'quantity' => $giftNum,
        ];
        $res = app('model_gift_box_prize')->insert($data);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '添加失败');
        }
    }

    /**
     * @api {Put} /giftbox/editboxgift 编辑盲盒奖池礼物
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} pond_type 奖池类型
     * @apiParam {Int} gift_info 礼物修改信息，格式：id,礼物id,数量。多个用分号;连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function editBoxGift(Request $request)
    {
        $pondType = $request->pond_type; //奖池类型
        $giftInfo = $request->gift_info; //礼物修改信息

        //查询该奖池里所有礼物id
        $pondGifts = app('model_gift_box_prize')->getChancePrizeList($pondType);
        $ids = array_column($pondGifts, 'id');

        //更新
        DB::beginTransaction();
        try {
            $giftInfo = explode(';', $giftInfo);
            foreach ($giftInfo as $v) {
                if ($v) {
                    $boxGift = explode(',', $v);
                    //id
                    if (isset($boxGift[0])) {
                        $id = $boxGift[0];
                        if (!in_array($id, $ids)) throw new BasicException(10001);
                    } else throw new BasicException(10001);
                    //礼物id
                    if (isset($boxGift[1])) {
                        $giftId = $boxGift[1];
                    } else throw new BasicException(10001);
                    //礼物数量
                    if (isset($boxGift[2])) {
                        $giftNum = $boxGift[2];
                    } else throw new BasicException(10001);

                    $this->paramVerify($giftId, $giftNum, $pondType, $id);

                    app('model_gift_box_prize')->where('id', $id)->update(['gift_id' => $giftId, 'quantity' => $giftNum]);
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    private function paramVerify($giftId, $giftNum, $pondType, $id = 0)
    {
        if (empty($giftId)) {
            throw new BasicException(0, '请选择礼物');
        }

        if (empty($giftNum) || !is_numeric($giftNum) || $giftNum < 0) {
            throw new BasicException(10001);
        }

        $exist = app('model_gift_box_prize')
            ->where(['type' => $pondType, 'gift_id' => $giftId])
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })
            ->value('id');
        if ($exist) throw new BasicException(0, '礼物已经存在');
    }

    /**
     * @api {Delete} /giftbox/delboxgift 删除盲盒奖池礼物
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {String} ids 盲盒礼物编号，多个用英文逗号连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function delBoxGift(Request $request)
    {
        $ids = $request->ids; //盲盒礼物编号
        if (empty($ids)) {
            throw new BasicException(10001);
        }

        $ids = explode(',', $ids);
        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if ($id) {
                    $giftBoxPrize = app('model_gift_box_prize')->select('type')->where('id', $id)->first();
                    if ($giftBoxPrize) app('model_gift_box_prize')->where('id', $id)->delete();
                }
            }
            DB::commit();
            app('redis')->del('box_boss_filter_big_gifts' . $giftBoxPrize->type);
            app('redis')->del('box_boss_filter_small_gifts' . $giftBoxPrize->type);
            app('redis')->del('box_boss_chance_gifts' . $giftBoxPrize->type);
            app('redis')->del('box_total_initial_weight' . $giftBoxPrize->type);
            app('redis')->del('box_preset_output_value' . $giftBoxPrize->type);
            app('redis')->del('box_default_input_value' . $giftBoxPrize->type);
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {Get} /giftbox/pricerecord 中奖记录
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} start_date 开始日期
     * @apiParam {Int} end_date 结束日期
     * @apiParam {Int} gift_id 礼物id，0：不限制
     * @apiParam {Int} keyword 搜索的关键词（用户昵称或用户id）
     * @apiParam {Int} page 第几页，默认1
     * @apiParam {Int} perpage 每页显示几条，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "list": {
    "current_page": 1,
    "data": [
    {
    "given_user_id": 547322, 用户ID
    "nickname": "小流氓💞", 用户昵称
    "gift_name": "小金表", 礼物名称
    "number": 1, 数量
    "p_type": 0,
    "type": 3, 类型：1：银盲盒；2：金礼盒；3：铜盲盒
    "id": 6388, 序号
    "add_time": "2021-04-30 18:15:15", 中奖时间
    "box_name": "金盲盒"
    }
    ],
    "first_page_url": "http://local.qipaoadmin/giftbox/pricerecord?page=1",
    "from": 1,
    "last_page": 306,
    "last_page_url": "http://local.qipaoadmin/giftbox/pricerecord?page=306",
    "next_page_url": "http://local.qipaoadmin/giftbox/pricerecord?page=2",
    "path": "http://local.qipaoadmin/giftbox/pricerecord",
    "per_page": 20,
    "prev_page_url": null,
    "to": 20,
    "total": 6104
    },
    "gift_list": [
    {
    "id": 283,
    "name": "蓝色夏威夷"
    },
    {
    "id": 288,
    "name": "玩具小熊"
    },
    {
    "id": 299,
    "name": "紫水晶"
    },
    {
    "id": 300,
    "name": "小金表"
    }
    ]
    }
    }
     */
    public function priceRecord(Request $request)
    {
        $startDate = $request->start_date;
        $endDate = $request->end_date;
        $giftId = $request->gift_id ?: 0;
        $keyword = $request->keyword;
        $perPage = $request->perpage ?: 10;

        $where = [];
        if ($giftId) {
            $where[] = ['gbpd.gift_id', '=', $giftId];
        }
        if ($startDate) {
            $where[] = ['gbpd.add_time', '>=', strtotime($startDate . ' 0:0:0')];
        }
        if ($endDate) {
            $where[] = ['gbpd.add_time', '<=', strtotime($startDate . ' 23:59:59')];
        }
        $fields = ['gbpd.given_user_id', 'ud.nickname', 'ud.user_code', 'g.name as gift_name', 'gbpd.number', 'gbpd.p_type', 'gbpd.type', 'gbpd.id', DB::raw("FROM_UNIXTIME(gbpd.add_time) as add_time")];
        $list = app('model_gift_box_prize_detail')->getListPaging($where, $keyword, $fields, $perPage);

        foreach ($list as &$v) {
            $v->box_name = $this->getBoxNameByType($v->type, $v->p_type);
        }

        return Response::sendData(['list' => $list]);
    }

    private function getBoxNameByType($type, $pType = 1)
    {
        $arr = [
            1 => '银',
            2 => '铜',
            3 => '金',
            4 => '铜',
            5 => '银',
            6 => '金',
            7 => '铜',
            8 => '银',
            9 => '金',
        ];
        return isset($arr[$type]) ? $arr[$type] . '盲盒' : $arr[$pType] . '盲盒';
    }

    /**
     * @api {Get} /giftbox/getpondtypes 根据盲盒类型获取奖池类型
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} box_type 盲盒类型：7铜盲盒(默认)，8银盲盒，9金盲盒
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    10,
    11,
    12,
    13,
    14
    ]
    }
     */
    public function getPondTypes(Request $request)
    {
        $boxType = $request->box_type ?: 7; //盲盒类型
        return Response::sendData(self::getPondTypesByBoxType($boxType));
    }

    //根据盲盒类型获取奖池类型
    private static function getPondTypesByBoxType($boxType)
    {
        $arr = [
            7 => [10, 11, 12, 13, 14],
            8 => [15, 16, 17, 18, 19],
            9 => [20, 21, 22, 23, 24],
        ];
        return isset($arr[$boxType]) ? $arr[$boxType] : [];
    }

    /**
     * @api {Get} /giftbox/pondset 个人奖池配置
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} pond_type 奖池类型，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 292,
    "initial_weight": 33,
    "type": 10,
    "gift_id": 304,
    "gift_name": "相依相慰",
    "price": 18800,
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f56e3ffb306a.png",
    "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f56e402eba6d.svga",
    "quantity": 200
    },
    {
    "id": 293,
    "initial_weight": 3,
    "type": 10,
    "gift_id": 288,
    "gift_name": "玩具小熊",
    "price": 999,
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f43848b74302.png",
    "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f43848e205d7.svga",
    "quantity": 0
    }
    ],
    }
    }
    }
     */
    public function pondSet(Request $request)
    {
        $pondType = $request->pond_type ?: 10; //奖池类型

        $list = app('model_gift_box_prize')->getChancePrizeList($pondType);
        $numTotal = app('model_gift_box_prize')->where(['type' => $pondType])->sum('quantity');
        $priceTotal = app('model_gift_box_prize')->from('ln_gift_box_prize as a')
            ->leftJoin('ln_gift as b', 'a.gift_id', '=', 'b.id')
            ->where(['a.type' => $pondType])
            ->sum(DB::raw('a.quantity * b.price'));

        return Response::sendData([
            'num_total' => $numTotal,
            'price_total' => $priceTotal,
            'list' => $list,
        ]);
    }

    /**
     * @api {Get} /giftbox/newuserlist 新手用户列表
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} config_value 配置值
     * @apiParam {Int} box_type 盲盒类型：7：铜；8：银；9：金
     * @apiParam {Int} keyword 搜索的关键字（用户编号）
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "list": {
    "current_page": 1,
    "data": [
    {
    "user_id": 643437, 用户id
    "set_value": "50000.00", 移除投入
    "inject": 14400, 投入值
    "remove_time": null,
    "nickname": "用户277527", 昵称
    "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/10.jpg", 头像
    "earnings": "2343710.00", 收益值
    "user_code": 277527, 用户编号
    "output_proportion": 22 产出比
    },
    {
    "user_id": 643447,
    "set_value": "1000.00",
    "inject": 600,
    "remove_time": null,
    "nickname": "撤筠593900",
    "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/12.jpg",
    "earnings": "300.00",
    "user_code": 593900,
    "output_proportion": 22
    }
    ],
    "first_page_url": "http://local.qipaoadmin/giftbox/newuserlist?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/giftbox/newuserlist?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/giftbox/newuserlist",
    "per_page": 20,
    "prev_page_url": null,
    "to": 13,
    "total": 13
    },
    "type": 7,
    "config_value": "1000"
    }
    }
     */
    public function newUserList(Request $request)
    {
        $configValue = $request->config_value ?: 0;
        $boxType = $request->box_type ?: 7;
        $keyword = trim($request->keyword);

        //修改配置
        if (7 == $boxType) $key = $this->tongKey;
        elseif (8 == $boxType) $key = $this->YingKey;
        else $key = $this->JinKey;
        $row = app('model_config')->where('key', $key)->first();
        if ($configValue && $configValue > 0 && is_numeric($configValue)) {
            if ($row) {
                app('model_config')->where('key', $key)->update(['value' => $configValue]);
            } else {
                app('model_config')->insert([
                    'key' => $key,
                    'value' => $configValue,
                    'group' => 1,
                    'name' => '盲盒投标',
                    'desc' => '盲盒投标'
                ]);
            }
        }
        $row = app('model_config')->where('key', $key)->first();

        $fields = ['gbu.user_id', 'gbu.set_value', 'gbu.inject', 'gbu.remove_time', 'ud.nickname', 'ud.head_picture', 'gbu.earnings', 'ud.user_code'];
        $where['gbu.remove_status'] = 0;
        $where['gbu.type'] = $boxType;
        if ($keyword) $where['ud.user_code'] = $keyword;
        $list = app('model_gift_box_user')->getUserList($where, $fields);
        foreach ($list as &$v) {
            $v->output_proportion = round($v->earnings/$v->inject, 2);
        }

        return Response::sendData(['list' => $list, 'box_type' => $boxType, 'config_value' => isset($row['value']) ? $row['value'] : 0]);
    }

    /**
     * @api {Get} /giftbox/userlist 个人用户奖池
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} box_type 盲盒类型：7：铜；8：银；9：金
     * @apiParam {Int} keyword 搜索的关键字（用户编号）
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "list": {
    "current_page": 1,
    "data": [
    {
    "user_id": 643437, 用户id
    "set_value": "50000.00", 移除投入
    "inject": 14400, 投入值
    "remove_time": null,
    "nickname": "用户277527", 昵称
    "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/10.jpg", 头像
    "earnings": "2343710.00", 收益值
    "user_code": 277527, 用户编号
    "output_proportion": 22
    },
    {
    "user_id": 643447,
    "set_value": "1000.00",
    "inject": 600,
    "remove_time": null,
    "nickname": "撤筠593900",
    "head_picture": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/avatar/12.jpg",
    "earnings": "300.00",
    "user_code": 593900,
    "output_proportion": 147
    }
    ],
    "first_page_url": "http://local.qipaoadmin/giftbox/newuserlist?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/giftbox/newuserlist?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/giftbox/newuserlist",
    "per_page": 20,
    "prev_page_url": null,
    "to": 13,
    "total": 13
    },
    "type": 7,
    "config_value": "1000"
    }
    }
     */
    public function userList(Request $request)
    {
        $boxType = $request->box_type ?: 7;
        $keyword = trim($request->keyword);

        $fields = ['gbu.user_id', 'gbu.set_value', 'gbu.inject', 'gbu.remove_time', 'ud.nickname', 'ud.head_picture', 'gbu.earnings', 'ud.user_code'];
        $where['gbu.remove_status'] = 1;
        $where['gbu.type'] = $boxType;
        if ($keyword) $where['ud.user_code'] = $keyword;
        $list = app('model_gift_box_user')->getUserList($where, $fields);
        foreach ($list as &$v) {
            $v->output_proportion = round($v->earnings/$v->inject, 2);
        }

        if (7 == $boxType) $key = $this->tongKey;
        elseif (8 == $boxType) $key = $this->YingKey;
        else $key = $this->JinKey;
        $configValue = app('model_config')->where(['key' => $key])->value('value');

        return Response::sendData(['list' => $list, 'box_type' => $boxType, 'config_value' => $configValue]);
    }

    /**
     * @api {Get} /giftbox/userpooldetail 个人用户奖池详情
     *
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} user_id 用户id，必须
     * @apiParam {Int} box_type 盲盒类型；7：铜，8：银，9：金
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": [
    {
    "id": 256,
    "gift_name": "紫水晶", 礼物名称
    "price": 18800, 礼物价格
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f56e0982f8c6.png", 图片
    "number": 22, 数量
    "gift_id": 299 礼物id
    },
    {
    "id": 173,
    "gift_name": "海洋女神",
    "price": 131400,
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f56e3e63cf22.png",
    "number": 0,
    "gift_id": 303
    },
    {
    "id": 172,
    "gift_name": "红玫瑰",
    "price": 600,
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f56e132250bc.png",
    "number": 991,
    "gift_id": 301
    }
    ]
    }
     */
    public function userPoolDetail(Request $request)
    {
        $userId = $request->user_id;
        $boxType = $request->box_type ?: 7;
        $list = app('model_gift_box_user_pond')->getList($userId, $boxType);
        return Response::sendData($list);
    }

    /**
     * @api {Post} /giftbox/userpoolgiftadd 添加个人用户奖池礼物
     *
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} user_id 用户id，必须
     * @apiParam {Int} box_type 盲盒类型；7：铜，8：银，9：金，必须
     * @apiParam {Int} gift_id 礼物id，必须
     * @apiParam {String} number 礼物数量，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function userPoolGiftAdd(Request $request)
    {
        $userId = $request->user_id;
        $boxType = $request->box_type;
        $giftId = $request->gift_id;
        $number = $request->number;

        $this->userPoolParamVerify($userId, $boxType, $giftId, $number);

        $res = app('model_gift_box_user_pond')->insert([
            'user_id' => $userId,
            'type' => $boxType,
            'gift_id' => $giftId,
            'number' => $number,
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '添加失败');
        }
    }

    /**
     * @api {Put} /giftbox/userpoolgiftedit 编辑个人用户奖池礼物
     *
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {Int} user_id 用户id，必须
     * @apiParam {Int} box_type 盲盒类型；7：铜，8：银，9：金
     * @apiParam {String} gift_info 礼物修改信息，格式：id,礼物id,数量。多个用分号;连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function userPoolGiftEdit(Request $request)
    {
        $userId = $request->user_id;
        $boxType = $request->box_type;
        $giftInfo = $request->gift_info; //礼物修改信息

        //查询该用户奖池里所有id
        $userPond = app('model_gift_box_user_pond')->select('id')->where(['user_id' => $userId, 'type' => $boxType])->get()->toArray();
        if (empty($userPond)) throw new BasicException(10001);
        $ids = array_column($userPond, 'id');
        //查询对应奖池里所有礼物id
        $gifts = app('model_gift')->select('id')->where('type', 8)->get()->toArray();
        $giftIds = array_column($gifts, 'id');

        //更新
        DB::beginTransaction();
        try {
            $giftInfo = explode(';', $giftInfo);
            foreach ($giftInfo as $v) {
                if ($v) {
                    $userPoolGift = explode(',', $v);
                    //id
                    if (isset($userPoolGift[0])) {
                        $id = $userPoolGift[0];
                        if (!in_array($id, $ids)) throw new BasicException(10001);
                    } else throw new BasicException(10001);
                    //礼物id
                    if (isset($userPoolGift[1])) {
                        $giftId = $userPoolGift[1];
                        if (!in_array($giftId, $giftIds)) throw new BasicException(10001);
                    } else throw new BasicException(10001);
                    //礼物数量
                    if (isset($userPoolGift[2])) {
                        $giftNum = $userPoolGift[2];
                    } else throw new BasicException(10001);

                    $this->userPoolParamVerify($userId, $boxType, $giftId, $giftNum, $id);

                    app('model_gift_box_user_pond')->where('id', $id)->update(['gift_id' => $giftId, 'number' => $giftNum]);
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    private function userPoolParamVerify($userId, $boxType, $giftId, $number, $id = 0)
    {
        $user = app('model_user')->where('user_id', $userId)->where('deleted', 0)->value('user_id');
        if (empty($user)) throw new BasicException(0, '参数错误：user_id');

        if (!in_array($boxType, [7, 8, 9])) throw new BasicException(0, '参数错误：box_type');

        if (empty($giftId)) throw new BasicException(0, '请选择礼物');

        $gift = app('model_gift')->where('type', 8)->where('id', $giftId)->where('sold', 1)->value('id');
        if (empty($gift)) throw new BasicException(0, '参数错误：gift_id');

        if (!is_numeric($number) || $number < 0) throw new BasicException(0, '礼物数量错误');

        $exist = app('model_gift_box_user_pond')
            ->where(['user_id' => $userId, 'gift_id' => $giftId, 'type' => $boxType])
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })
            ->value('id');
        if ($exist) throw new BasicException(0, '礼物已经存在');
    }

    /**
     * @api {Delete} /giftbox/userpoolgiftdel 删除个人用户奖池礼物
     *
     * @apiGroup 补充接口-盲盒管理
     *
     * @apiParam {String} ids 要删除的id，多个用英文逗号,连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function userPoolGiftDel(Request $request)
    {
        $ids = $request->ids;

        $ids = str_replace('"', '', $ids);
        $ids = str_replace('\'', '', $ids);
        $ids = str_replace(' ', '', $ids);
        $ids = explode(',', $ids);

        //更新
        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                if ($id) {
                    $exist = app('model_gift_box_user_pond')->select('id')->where('id', $id)->first();
                    if ($exist) app('model_gift_box_user_pond')->where('id', $id)->delete();
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {Get} /giftbox/boxgiftlist 盲盒奖品列表
     *
     * @apiGroup 补充接口-病毒大作战
     *
     * @apiParam {Int} type 类型：1：银盲盒；2：铜盲盒；3：金盲盒
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "theory_times": "2653", 理论次数
    "theory_input": 530600, 理论投入金币
    "theory_output": 16548200, 理论产出金币
    "theory_ratio": 0.3367, 理论产出比
    "input_all_gold": 10282800, 加库存投入
    "output_all_gold": 22517557314, 加库存产出
    "real_output_radio": 0.0005, 加库存产出比
    "total_count_real": "189993", 实际次数
    "total_real": "901690800.00", 实际投入金币
    "output_real": "25165269314.00", 实际产出金币
    "ratio_real": 0.0358, 实际产出比
    "type": 1,
    "pot_name": "银盲盒",
    "list": [
    {
    "id": 639,
    "initial_weight": 11, 初始权重
    "type": 1,
    "gift_id": 300, 礼物id
    "gift_name": "小金表", 礼物名称
    "price": 1000000, 礼物价格
    "picture": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f56e0bb220d8.png", 图片
    "special": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5f56e0bebdbf7.svga",
    "quantity": 0,
    "initial_chance": 0.415, 初始权重百分比，展示的时候加上%
    "revise_weight": 0, 修正权重
    "revise_chance": 0, 修正权重百分比，展示的时候加上%
    "win_prize_num": "154", 中奖格式
    "win_prize_gold": "800800.00", 中奖金币
    "real_chance": 0.27599999999999997 实际概率
    }
    ]
    }
    }
     */
    public function boxGiftList()
    {
        $price = $this->price;
        $data = app('model_gift_box_prize')->getChancePrizeList($this->type);
        $revise_weights = app('redis')->get('box_revise_weights' . $this->type);
        if ($revise_weights){
            //获取所有修正权重的累加和
            $all_revise_weight = array_column($revise_weights,'revise_weight','id');
            $sum_revise_chance = array_sum($all_revise_weight);
        } else {
            $sum_revise_chance = 0;
        }
        $sum_initial_chance = app('model_gift_box_prize')->where('type', $this->type)->sum('initial_weight');
        if (!$sum_initial_chance){
            $sum_initial_chance = 0;
        }

        $theory_output =0;
        if (!empty($data)) {
            foreach ($data as $ky => $vl){
                $theory_output += ($vl['price'] * $vl['initial_weight']);
                if ($sum_initial_chance!= 0) {
                    $initial_chance = round($vl['initial_weight']/$sum_initial_chance,5) *100;
                } else {
                    $initial_chance = 0;
                }
                $data[$ky]['initial_chance'] = $initial_chance;

                if ($sum_revise_chance == 0) {
                    $revise_chance =0;
                    $data[$ky]['revise_weight'] = 0;
                } else {
                    if (isset($all_revise_weight[$vl['id']])) {
                        $revise_chance =round($all_revise_weight[$vl['id']]/$sum_revise_chance,5) *100;
                        $data[$ky]['revise_weight'] =$all_revise_weight[$vl['id']];
                    } else {
                        $revise_chance =0;
                        $data[$ky]['revise_weight'] = 0;
                    }
                }
                $data[$ky]['revise_chance'] =$revise_chance;
                $win_prize_num = app('model_gift_box_prize_detail')->where(['gift_id'=>$vl['gift_id'],'type'=>$vl['type']])->sum('number');
                if (!$win_prize_num){
                    $win_prize_num =0;
                }
                $win_prize_gold = app('model_gift_box_prize_detail')->where(['gift_id'=>$vl['gift_id'],'type'=>$vl['type']])->sum('gold_coin');
                if (!$win_prize_gold){
                    $win_prize_gold =0;
                }
                //该分类下该奖品的中奖个数
                $data[$ky]['win_prize_num'] =$win_prize_num;
                //该分类下该奖品的中奖金币数
                $data[$ky]['win_prize_gold'] =$win_prize_gold;

                //该分类所有中奖个数
                $win_prize_all = app('model_gift_box_prize_detail')->where(['type'=>$vl['type']])->sum('number');
                if (!$win_prize_all){
                    $win_prize_all =0;
                }
                //实际概率= 该分类下该奖品的中奖个数/该分类所有奖品中奖个数
                if ($win_prize_all !=0){
                    $real_chance = round($win_prize_num/$win_prize_all,5)*100;
                }else{
                    $real_chance =0;
                }
                $data[$ky]['real_chance'] =$real_chance;
            }
        }

        //预设投入值
        $default_input_value = app('redis')->get('box_default_input_value'.$this->type);
        if (!$default_input_value){
            $sum_initial_chance_default = app('model_gift_box_prize')->where('type', $this->type)->sum('initial_weight');
            $default_input_value = $sum_initial_chance_default*$price;
            app('redis')->setex('box_default_input_value'.$this->type, 60480000,$default_input_value);
        }
        //预设产出值
        // $preset_output_value =C('BOX_PRESET_OUTPUT_VALUE');
        $preset_output_value = app('redis')->get('box_preset_output_value'.$this->type);
        if (!$preset_output_value){
            $preset_output_value =0;
            $this_type_gifts = app('model_gift_box_prize')->from('ln_gift_box_prize as a')
                ->select('a.id', 'a.initial_weight', 'b.price')
                ->leftJoin('ln_gift as b', 'a.gift_id', '=', 'b.id')
                ->where(['a.type' => $this->type])
                ->get()->toArray();
            if ($this_type_gifts){
                foreach ($this_type_gifts as $k=>$this_type_gift){
                    $preset_output_value += ($this_type_gift['price']*$this_type_gift['initial_weight']);
                }
            }
            app('redis')->setex('box_preset_output_value'.$this->type, 60480000,$preset_output_value);
        }
        //投入金币数量
        $input_all_gold = app('model_gift_box_price')->sum('this_time_gold');
        if (!$input_all_gold){
            $input_all_gold =0;
        }
        $input_real_all_gold = $input_all_gold;
        $input_all_gold = $input_real_all_gold+$default_input_value;

        //产出金币数量
        $output_all_gold = app('model_gift_box_price')->sum('number');
        if (!$output_all_gold){
            $output_all_gold =0;
        }
        $output_real_all_gold = $output_all_gold;
        $output_all_gold = $output_real_all_gold+$preset_output_value;

        //如果是初始值得两倍则减掉初始值
        for ($x=0; $x<=99999999; $x++) {
            if ($input_all_gold >(2*$default_input_value) && $output_all_gold>(2*$preset_output_value)){
                $input_all_gold = $input_all_gold -$default_input_value;
                $output_all_gold = $output_all_gold -$preset_output_value;
            }else{
                break;
            }
        }
        if ($output_all_gold !=0){
            $real_output_radio = round($input_all_gold/$output_all_gold,4);
        }else{
            $real_output_radio =0;
        }
        if ($output_real_all_gold !=0){
            $ratio_real = round($input_real_all_gold/$output_real_all_gold,4);
        }else{
            $ratio_real =0;
        }
        if ($theory_output!=0){

            $theory_ratio =round($sum_initial_chance*$price/$theory_output,4);
        }else{
            $theory_ratio =0;
        }

        $total_count_real = app('model_gift_box_price')->sum('count');
        $returnData = [
            //理论值
            'theory_times'=>$sum_initial_chance, //理论次数
            'theory_input'=>$sum_initial_chance*200, //理论投入金币
            'theory_output'=>$theory_output, //理论产出金币
            'theory_ratio'=>$theory_ratio, //理论产出比
            //加库存值
            'input_all_gold'=>$input_all_gold, //加库存投入
            'output_all_gold'=>$output_all_gold, //加库存产出
            'real_output_radio'=>$real_output_radio, //加库存产出比
            //实际值
            'total_count_real'=>$total_count_real, //实际次数
            'total_real'=>$input_real_all_gold, //实际投入金币
            'output_real'=>$output_real_all_gold, //实际产出金币
            'ratio_real'=>$ratio_real, //实际产出比

            'type'=>$this->type, //类型
            'pot_name'=>$this->pot_name, //类型名称
            'list'=>$data,
        ];

        return Response::sendData($returnData);
    }

    /**
     * @api {Post} /giftbox/boxgiftadd 盲盒奖品新增
     *
     * @apiGroup 补充接口-病毒大作战
     *
     * @apiParam {Int} type 类型：1：银盲盒；2：铜盲盒；3：金盲盒
     * @apiParam {Int} gift_id 礼物id
     * @apiParam {Int} initial_weight 初始权重
     * @apiParam {Int} percent 百分比，默认为1
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function boxGiftAdd(Request $request)
    {
        $giftId = $request->gift_id; //礼物id
        $initialWeight = $request->initial_weight; //初始权重
        $percent = $request->percent ?: 1; //百分比

        $this->boxGiftVerify($giftId, $initialWeight, $percent);

        $res = app('model_gift_box_prize')->insert([
            'gift_id' => $giftId,
            'type' => $this->type,
            'initial_weight' => $initialWeight,
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '新增失败');
        }
    }

    /**
     * @api {Put} /giftbox/boxgiftedit 盲盒奖品编辑
     *
     * @apiGroup 补充接口-病毒大作战
     *
     * @apiParam {Int} type 类型：1：银盲盒；2：铜盲盒；3：金盲盒
     * @apiParam {Int} id 礼物id
     * @apiParam {Int} gift_id 礼物id
     * @apiParam {Int} initial_weight 初始权重
     * @apiParam {Int} percent 百分比，默认为1
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function boxGiftEdit(Request $request)
    {
        $id = $request->id; //礼物id
        $giftId = $request->gift_id; //礼物id
        $initialWeight = $request->initial_weight; //初始权重
        $percent = $request->percent ?: 1; //百分比

        $exist = app('model_gift_box_prize')->where('id', $id)->value('id');
        if (!$exist) throw new BasicException(0, '参数错误');

        $this->boxGiftVerify($giftId, $initialWeight, $percent, $id);

        $res = app('model_gift_box_prize')->where('id', $id)->update([
            'gift_id' => $giftId,
            'initial_weight' => $initialWeight,
        ]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '编辑失败');
        }
    }

    private function boxGiftVerify($giftId, $initialWeight, $percent = 1, $id = 0)
    {
        if (empty($giftId)) throw new BasicException(0, '请选择礼物');
        $gift = app('model_gift')->where(['id' => $giftId, 'type' => 8])->value('id');
        if (!$gift) throw new BasicException(0, '礼物id错误');
        $exist = app('model_gift_box_prize')
            ->where(['gift_id' => $giftId, 'type' => $this->type])
            ->where(function ($query) use ($id) {
                if ($id > 0) {
                    $query->where('id', '<>', $id);
                }
            })
            ->value('id');
        if ($exist) throw new BasicException(0, '礼物已经存在');
        if (!is_numeric($initialWeight)) throw new BasicException(0, '初始权重有误');

        app('redis')->del('box_boss_filter_big_gifts'.$this->type);
        app('redis')->del('box_boss_filter_small_gifts'.$this->type);
        app('redis')->del('box_boss_chance_gifts'.$this->type);
        app('redis')->del('box_total_initial_weight'.$this->type);
        app('redis')->del('box_preset_output_value'.$this->type);
        app('redis')->del('box_default_input_value'.$this->type);
        app('redis')->del('box_boss_filter_big_gifts4'.$percent);
    }

    /**
     * @api {Delete} /giftbox/boxgiftdel 盲盒奖品删除
     *
     * @apiGroup 补充接口-病毒大作战
     *
     * @apiParam {Int} type 类型：1：银盲盒；2：铜盲盒；3：金盲盒
     * @apiParam {Int} ids 礼物id，多个用英文下的逗号连接
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function boxGiftDel(Request $request)
    {
        $ids = $request->ids;
        $ids = str_replace('"', '', $ids);
        $ids = str_replace('\'', '', $ids);
        $ids = str_replace(' ', '', $ids);
        $ids = explode(',', $ids);

        DB::beginTransaction();
        try {

            foreach ($ids as $id) {
                if ($id) {
                    $exist = app('model_gift_box_prize')->where('id', $id)->value('id');
                    if ($exist) {
                        app('model_gift_box_prize')->where('id', $id)->delete();
                    } else {
                        throw new BasicException(10001);
                    }
                }
            }
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }
}
